package main;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import config.ServletConfig;
import http.Request;
import http.Response;
import servlet.Servlet;

public class Tomcat {
	private int port=9090;
	
	public void start(){
		try {
			while(true){
				ServerSocket socket = new ServerSocket(port);
				Socket accept = socket.accept();
				InputStream inputStream = accept.getInputStream();
				OutputStream outputStream = accept.getOutputStream();
				Request request = new Request(inputStream);
				Response response = new Response(outputStream);
				doServlet(request,response);
				inputStream.close();
				accept.close();
				socket.close();
				//8888
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doServlet(Request request,Response response){
		try {
			Servlet servlet = ServletConfig.getServlet(request.getUrl());
			if(servlet==null){
				response.write("404,not find servlet");
			}else{
				servlet.service(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new Tomcat().start();

	}

}
